<template>
    <div>
        <el-dialog :title="dialogTitle" :visible.sync="addDialogShow" width="800px" :close-on-click-modal="false" :before-close="dialogHandleCancel">
            <span class="madp-category-text">新增可见范围设置，管理员可根据不同部门选择展示不同话术，部门管理员可创建部门可见的话术</span>
            <el-form v-if="addDialogShow" ref="addForm" label-width="130px" :model="addForm" :rules="rules">
                <el-form-item label="分组名称:" prop="name" v-if="isShow">
                    <el-input maxlength="4" v-model.trim="addForm.name" placeholder="请输入分组名称"></el-input>
                </el-form-item>
                <el-form-item label="设置子分组:" v-if="isShow">
                    <el-input
                        v-model.trim="addForm.childrenName"
                        placeholder="请输入子分组名称，按回车完成，多个标签用‘，’（中文）隔开"
                        @input="updateInput"
                        @keyup.enter.native="handleInputConfirm"
                    ></el-input>
                </el-form-item>
                <el-form-item v-show="addForm.children && addForm.children.length > 0" v-if="dialogType != 'visibleRange'">
                    <div v-for="(tag, index) in addForm.children" :key="tag.key" class="madp-tag-item">
                        <el-input class="tag-input" v-model.trim="tag.name" placeholder="请输入子分组名称" maxlength="4"></el-input>
                        <i class="el-icon-bottom" v-show="index != addForm.children.length - 1" @click="handleDown(index)"></i>
                        <i class="el-icon-top" v-show="index != 0" @click="handleUp(index)"></i>
                        <i class="el-icon-close" @click="handleClose(index, tag)"></i>
                    </div>
                </el-form-item>
                <el-form-item label="可见范围:" prop="visibleRange">
                    <el-radio-group v-model="addForm.visibleRange" :disabled="dialogType == 'viewVisibleRange'">
                        <el-radio :label="1">全部员工</el-radio>
                        <el-radio :label="2">部门可见</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="选择可用部门:" v-if="addForm.visibleRange == 2">
                    <el-button type="primary" @click="selectDepart">请选择选择可用部门</el-button>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="dialogHandleCancel">取消</el-button>
                <el-button type="primary" @click="dialogHandleSubmit">确定</el-button>
            </div>
        </el-dialog>
        <el-dialog :title="dialogIsEdit ? '查看指定部门' : '选择指定部门'" :visible.sync="dialogShow" width="40%" :close-on-click-modal="false">
            <el-tree v-if="dialogShow" ref="tree" :data="departTree" show-checkbox node-key="id" :default-checked-keys="defaultMultipleValue" :props="defaultProps"></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogShow = false" :type="dialogIsEdit ? 'primary' : ''">{{ dialogIsEdit ? '确定' : '取消' }}</el-button>
                <el-button v-show="!dialogIsEdit" type="primary" @click="handleSubmit">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import { fetchTree } from '@/api/admin/dept';
export default {
    props: {
        form: {
            type: Object,
            default: function() {
                return {
                    name: '',
                    visibleRange: 1,
                    deptIds: [],
                    children: []
                };
            }
        },
        addDialogShow: {
            type: Boolean
        },
        dialogTitle: {
            type: String
        },
        dialogType: {
            type: String
        }
    },
    data() {
        return {
            // 表单
            addForm: {},
            // 部门树数据
            departTree: [],
            // 选择部门弹窗开关
            dialogShow: false,
            // 树组件props
            defaultProps: {
                children: 'children',
                label: 'name',
                disabled: 'disabled'
            },
            // 是否编辑
            dialogIsEdit: false,
            // 多选部门内容
            defaultMultipleValue: [],
            // 表单校验规则
            rules: {
                name: [
                    {
                        required: true,
                        message: '请输入分组名称',
                        trigger: 'blur'
                    }
                ],
                visibleRange: [
                    {
                        required: true,
                        message: '请选择可见范围',
                        trigger: 'change'
                    }
                ]
            }
        };
    },
    watch: {
        addDialogShow: {
            handler(val) {
                if (val) {
                    this.initForm();
                    this.initTree();
                }
            }
        }
    },
    computed: {
        isShow() {
            return !['viewVisibleRange', 'visibleRange'].includes(this.dialogType);
        }
    },
    methods: {
        // 初始化表单数据
        initForm() {
            this.addForm = JSON.parse(JSON.stringify(this.form));
            console.log('this.addForm', this.addForm);
        },
        // 初始树数据
        initTree() {
            fetchTree().then((res) => {
                this.departTree = res.data.data;
            });
        },
        // 获取部门树数据
        selectDepart() {
            this.departTree = this.reduceArr(this.departTree, !Boolean(this.dialogType == 'viewVisibleRange'));
            let arr = [];
            if (this.addForm.depts && this.addForm.depts.length > 0) {
                this.addForm.depts.map((i) => {
                    if (i.deptId) {
                        arr.push(i.deptId);
                    } else {
                        arr.push(i);
                    }
                });
                this.defaultMultipleValue = arr;
            } else {
                this.defaultMultipleValue = [];
            }
            this.dialogShow = true;
        },
        // 数组处理
        reduceArr(data, flag) {
            data.map((i) => {
                if (flag) {
                    delete i.disabled;
                } else {
                    i.disabled = true;
                }
                if (i.children && i.children.length > 0) {
                    this.reduceArr(i.children, flag);
                }
            });
            return data;
        },
        // 确定部门选择
        handleSubmit() {
            let checkIds = this.$refs.tree.getCheckedKeys();
            if (checkIds.length < 1) return this.$message.warning('请选择可见范围');
            this.defaultMultipleValue = checkIds;
            this.addForm.deptIds = this.defaultMultipleValue;
            this.dialogShow = false;
        },
        // 弹窗点击取消
        dialogHandleCancel() {
            this.$emit('dialogHandleCancel');
        },
        // 弹窗点击确定
        dialogHandleSubmit() {
            let { deptIds, depts } = this.addForm;
            if (this.addForm.visibleRange == 2 && (deptIds ? deptIds.length : 0 + depts ? depts.length : 0) == 0) {
                this.$message.warning('请选择部门');
                return;
            } else if (this.addForm.visibleRange == 1) {
                delete this.addForm.deptIds;
                delete this.addForm.depts;
            }
            this.handleInputConfirm();
            this.$refs.addForm.validate((valid) => {
                if (valid) {
                    this.$emit('dialogHandleSubmit', this.addForm);
                }
            });
        },
        // 删除单个标签
        handleClose(index, tag) {
            if (tag.id) this.addForm.needConfirm = true;
            this.addForm.children.splice(index, 1);
            this.$forceUpdate();
        },
        // 标签上移
        handleUp(index) {
            let item = JSON.parse(JSON.stringify(this.addForm.children[index]));
            this.addForm.children[index] = this.addForm.children[index - 1];
            this.addForm.children[index - 1] = item;
            this.$forceUpdate();
        },
        // 标签下移
        handleDown(index) {
            let item = JSON.parse(JSON.stringify(this.addForm.children[index]));
            this.addForm.children[index] = this.addForm.children[index + 1];
            this.addForm.children[index + 1] = item;
            this.$forceUpdate();
        },
        // 处理input框添加标签
        handleInputConfirm() {
            if (this.addForm.childrenName) {
                let inputArr = this.addForm.childrenName.split('，');
                inputArr.map((item, index) => {
                    let flag =
                        item.trim() == '' ||
                        this.addForm.children.some((i) => {
                            return i.name == item;
                        });
                    if (!flag) {
                        this.addForm.children.push({
                            name: item,
                            key: Math.random().toFixed(5) + index * Math.random().toFixed(5)
                        });
                    }
                });
                this.addForm.childrenName = '';
            }
        },
        // 更新输入内容
        updateInput() {
            let str = this.addForm.childrenName;
            str = str.replace(/\s+/g, '');
            let arr = str.split('，');
            arr = arr.map((i) => {
                if (i.length > 6) {
                    i = i.slice(0, 6);
                }
                return i;
            });
            this.addForm.childrenName = arr.join('，');
        }
    }
};
</script>
<style scoped lang="scss">
.madp-category-text {
    background: #effaff;
    display: inline-block;
    margin-bottom: 20px;
}
.madp-tag-item {
    display: flex;
    margin-bottom: 5px;
    .tag-input {
        width: 80%;
    }
    i {
        margin: 0.5rem;
        font-size: 1rem;
        cursor: pointer;
    }
}
</style>
